package com.arron.algorithm.leetcodetop100.滑动窗口;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 38. 找到字符串中所有字母异位词
 */
public class 找到字符串中所有字母异位词 {


    public List<Integer> findAnagrams(String s, String p) {
            //两个hashmap
        Map<Character,Integer> window = new HashMap<>();
        Map<Character,Integer> need = new HashMap<>();

        List<Integer> res = new ArrayList<>();


        for (char c : p.toCharArray()) {
            need.put(c,need.getOrDefault(c,0)+1);
        }

        int l = 0,r = 0;
        int valid = 0;

        while (r < s.length()){

            char c = s.charAt(r);
            r++;

            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if (window.get(c).equals(need.get(c))){
                    valid++;
                }
            }

            //移动窗口
            if (r-l >= p.length()){

                if (valid == need.size()){
                    res.add(l);
                }

                //更新valid值
                if (need.containsKey(s.charAt(l))){

                    if (window.get(s.charAt(l)).equals(need.get(s.charAt(l)))){
                        valid--;
                    }
                    window.put(s.charAt(l),window.get(s.charAt(l))-1);
                }

                //左指针移动
                l++;
            }
        }

        return res;
    }

}
